<template>
  <div class="mod-config">
    <el-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="outerVisible "
      width="100%">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
               label-width="120px">

        <el-row>
          <el-form-item label="客户" prop="clientName">
            <!--      <el-input v-model="dataForm.clientName" placeholder="租户ID"></el-input>-->
            <el-autocomplete v-model="dataForm.clientName" style="width: 100%"
                             :fetch-suggestions="querySearchClient" placeholder="请输入客户名称"
                             popper-class="select-option"
                             @select="handleClientSelect"></el-autocomplete>
          </el-form-item>
          <el-form-item label="账户" prop="accountName">
            <!--        <el-input v-model="dataForm.accountId" placeholder="账户ID"></el-input>-->
            <el-autocomplete v-model="dataForm.accountName" style="width: 100%"
                             :fetch-suggestions="querySearchAccount" placeholder="请输入账户名称"
                             popper-class="select-option"
                             @select="handleAccountSelect"></el-autocomplete>
          </el-form-item>

          <el-form-item label="收款单据编号" prop="code">
            <el-input v-model="dataForm.code" placeholder="收款单据编号">
              <el-button slot="append" icon="el-icon-search" @click="getLastCode(dataForm)"></el-button>
            </el-input>
          </el-form-item>
        </el-row>

        <el-row>

          <el-form-item label="收款日期" prop="receiptDate">
            <el-date-picker type="date" v-model="dataForm.receiptDate" @on-change="saleDateChange"
                            placeholder="收款日期" :editable="false" style="width: 100%"></el-date-picker>
          </el-form-item>

          <el-form-item label="收款金额(元)" prop="receiptAmount">
            <el-input-number v-model="dataForm.receiptAmount" controls-position="right" style="width: 100%"
                             :precision="2" :step="0.1" :min="0" @change="checkReceiptAmount()"></el-input-number>
          </el-form-item>
        </el-row>
        <el-row>

          <!--        <ReceiptDetails ref="receiptDetailsData"></ReceiptDetails>-->

          <el-form-item>
            <el-button v-if="isAuth('funds:receiptdetail:save')" type="primary" @click="addRow">新增</el-button>
            <el-button v-if="isAuth('funds:receiptdetail:delete')" type="danger" @click="deleteHandle()"
                       :disabled="dataListSelections.length <= 0">批量删除
            </el-button>
            <el-button v-if="isAuth('funds:receiptdetail:distribution')" type="success" @click="distribution">分配收款金额
            </el-button>
          </el-form-item>
          <el-table
            :data="dataList"
            border
            :summary-method="getSummaries"
            show-summary
            v-loading="dataListLoading"
            @selection-change="selectionChangeHandle"
            :row-class-name="tableRowClassName"
            style="width: 100%; margin-top: 20px">
            <el-table-column
              type="selection"
              header-align="center"
              align="center"
              width="50">
            </el-table-column>

            <el-table-column
              prop="saleOrderName"
              header-align="center"
              align="center"
              width="250px"
              label="销售订单">
              <template slot-scope="scope">
                <!--              <el-autocomplete v-if="scope.row.status" v-model="scope.row.saleOrderName"-->
                <!--                               :fetch-suggestions="querySearchAsync" placeholder="请输入内容"-->
                <!--                               @select="handleNameSelect($event, scope.row)"-->
                <!--                               popper-class="select-option"-->
                <!--              ></el-autocomplete>-->

                <el-input v-if="scope.row.status" v-model="scope.row.saleOrderName" popper-class="select-option"
                          @focus="saleOrderSelectHandle()"
                ></el-input>

                <span v-else>{{scope.row.saleOrderName}}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="saleDate"
              header-align="center"
              align="center"
              label="销售日期">
            </el-table-column>
            <el-table-column
              prop="saleTotalAmount"
              header-align="center"
              align="center"
              label="单据金额">
            </el-table-column>
            <el-table-column
              prop="deposit"
              header-align="center"
              align="center"
              label="定金">
            </el-table-column>
            <el-table-column
              prop="writtenOffAmount"
              header-align="center"
              align="center"
              label="已核销金额">
            </el-table-column>
            <el-table-column
              prop="remainAmount"
              header-align="center"
              align="center"
              label="未核销金额">
            </el-table-column>
            <el-table-column
              prop="writtenOffNum"
              header-align="center"
              align="center"
              label="已核销次数">
            </el-table-column>
            <el-table-column
              prop="thisWrittenOffAmount"
              header-align="center"
              align="center"
              label="本次核销金额">
              <template slot-scope="scope">
                <el-input v-if="scope.row.status" v-model="scope.row.thisWrittenOffAmount"
                          @keyup.native="scope.row.thisWrittenOffAmount = oninputMoney(scope.row.thisWrittenOffAmount)"
                          @change="checkThisWrittenOffAmount(scope.row)"
                ></el-input>
                <span v-else>{{scope.row.thisWrittenOffAmount}}</span>
              </template>
            </el-table-column>

            <el-table-column
              prop="remark"
              header-align="center"
              align="center"
              label="备注">
              <template slot-scope="scope">
                <el-input v-if="scope.row.status" v-model="scope.row.remark"
                ></el-input>
                <span v-else>{{scope.row.remark}}</span>
              </template>

            </el-table-column>
            <el-table-column
              fixed="right"
              header-align="center"
              align="center"
              width="150"
              label="操作">
              <template slot-scope="scope">
                <el-button class="el-icon-edit" type="primary" :disabled="scope.row.status==1"
                           size="small" circle @click.native.prevent="editRow(scope.row)"></el-button>
                <el-button class="el-icon-delete" type="danger"
                           size="small" circle @click.native.prevent="deleteRow(scope.$index, dataList)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="totalPage"
            layout="total, sizes, prev, pager, next, jumper">
          </el-pagination>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="outerVisible  = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>

      <!-- 弹窗, 新增 / 修改 -->
      <saleOrderSelect v-if="saleOrderSelectVisible" ref="saleOrderSelect"></saleOrderSelect>
    </el-dialog>
  </div>
</template>

<script>
  import saleOrderSelect from './sale-order-select.vue'
  import Utils from '../../../utils/event.js'

  export default {
    components: {
      saleOrderSelect
    },
    activated () {
      // this.getDataList()
      this.getReceiptDetailsByHeadId(this.dataForm.headerId)
    },
    data () {
      return {
        outerVisible: false,
        clientIdForSearch: '',
        dataForm: {
          headerId: 0,
          id: 0,
          status: '',
          deleted: '',
          createTime: '',
          createUserId: '',
          tenantId: '',
          name: '',
          code: '',
          clientId: '',
          clientName: '',
          accountId: '',
          accountName: '',
          receiptDate: '',
          receiptAmount: ''
        },
        formDto: {
          receiptDetailList: [],
          deleteReceiptDetailList: []
        },
        dataRule: {
          name: [
            {required: true, message: '收款单据名称不能为空', trigger: 'blur'}
          ],
          code: [
            {required: true, message: '收款单据编号不能为空', trigger: 'blur'}
          ],
          receiptDate: [
            {required: true, message: '收款日期不能为空', trigger: 'blur'}
          ],
          receiptAmount: [
            {required: true, message: '收款金额不能为空', trigger: 'blur'}
          ]
        },
        dataList: [],
        delList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        thisWrittenOffAmount: 0,
        clientId: '',
        saleOrderSelectVisible: false
      }
    },
    mounted () {
      var that = this
      Utils.$on('demo', function (msg) {
        console.log(msg)
        that.refreshDataListForOrders(msg)
      })
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.outerVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          // if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/funds/receipt/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.status = data.receipt.status
              this.dataForm.deleted = data.receipt.deleted
              this.dataForm.createTime = data.receipt.createTime
              this.dataForm.createUserId = data.receipt.createUserId
              this.dataForm.tenantId = data.receipt.tenantId
              this.dataForm.name = data.receipt.name
              this.dataForm.code = data.receipt.code
              this.dataForm.clientId = data.receipt.clientId
              this.dataForm.clientName = data.receipt.clientName
              this.dataForm.accountId = data.receipt.accountId
              this.dataForm.accountName = data.receipt.accountName
              this.dataForm.receiptDate = data.receipt.receiptDate
              this.dataForm.receiptAmount = data.receipt.receiptAmount

              this.getInitData()

              // this.$refs.receiptDetailsData.getReceiptDetailsByHeadId(this.dataForm.id)
              this.getReceiptDetailsByHeadId(this.dataForm.id)
            }
          })
        })
      },
      // 表单提交
      dataFormSubmit () {
        // eslint-disable-next-line eqeqeq
        if (this.thisWrittenOffAmount != this.dataForm.receiptAmount) {
          this.$message({
            message: '收款金额与本次核销金额总和不同',
            type: 'warning'
          })
          return
        }
        // JS判断一个数组中是否有重复值的三种方法
        let nary = this.dataList.sort()
        if (nary.length > 1) {
          for (let i = 0; i < nary.length; i++) {
            if (i + 1 < nary.length) {
              // eslint-disable-next-line eqeqeq
              if (nary[i].salesOrderHeaderId == nary[i + 1].salesOrderHeaderId) {
                this.$message({
                  message: '不能有重复的销售单',
                  type: 'warning'
                })
                return
              }
            }
          }
        }

        // 订单明细
        this.formDto.receiptDetailList = this.dataList
        this.formDto.deleteReceiptDetailList = this.delList

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/funds/receipt/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'status': this.dataForm.status,
                'deleted': this.dataForm.deleted,
                'createTime': this.dataForm.createTime,
                'createUserId': this.dataForm.createUserId,
                'tenantId': this.dataForm.tenantId,
                // 'name': this.dataForm.name,
                'name': this.dataForm.code,
                'code': this.dataForm.code,
                'clientId': this.dataForm.clientId,
                'clientName': this.dataForm.clientName,
                'accountId': this.dataForm.accountId,
                'accountName': this.dataForm.accountName,
                'receiptDate': this.dataForm.receiptDate,
                'receiptAmount': this.dataForm.receiptAmount,

                'receiptDetailList': this.formDto.receiptDetailList,
                'deleteReceiptDetailList': this.formDto.deleteReceiptDetailList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.outerVisible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 客户 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchClient (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/client/listClients/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.clients = data.clientsMap.clientNameDtoList
          } else {
            this.clients = []
          }
        })
        // callback(this.clients)
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.clients)
        }, 500)
      },
      handleClientSelect (item) {
        console.log(item)
        // do something
        this.dataForm.clientId = item.clientId
        this.clientIdForSearch = item.clientId
        this.dataForm.clientName = item.value
      },
      // 账户 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchAccount (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null ? 'undefined' : queryString
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sto/account/listAccounts/${this.s_girard}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.accounts = data.accountsMap.accountNameDtoList
          } else {
            this.accounts = []
          }
        })
        // callback(this.clients)
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.accounts)
        }, 500)
      },
      handleAccountSelect (item) {
        console.log(item)
        // do something
        this.dataForm.accountId = item.accountId
        this.dataForm.accountName = item.accountName
      },
      // 获取最新的编号
      getLastCode (dataForm) {
        this.$http({
          url: this.$http.adornUrl(`/funds/receipt/getLastCode`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            dataForm.code = data.lastCode
          } else {
            dataForm.code = ''
          }
        })
      },
      getInitData () {
        // 收款日期，默认显示今天
        this.dataForm.receiptDate = new Date()
      },
      saleDateChange (data) {
        this.dataForm.receiptDate = new Date(data)
      },
      refreshDataListForOrders (dataListSelections) {
        // this.dataList.concat(dataListSelections)
        // this.dataList = dataListSelections

        let index = this.dataList.findIndex((value) => value.saleOrderName === '')

        this.dataList.splice(index, 1)

        for (var i = 0; i < dataListSelections.length; i++) {
          this.dataList.push({
            saleOrderName: dataListSelections[i].saleOrderName,
            salesOrderHeaderId: dataListSelections[i].salesOrderHeaderId,
            saleOrderCode: dataListSelections[i].saleOrderCode,
            deposit: dataListSelections[i].deposit,
            writtenOffAmount: dataListSelections[i].writtenOffAmount,
            remainAmount: dataListSelections[i].remainAmount,
            saleDate: dataListSelections[i].saleDate,
            thisWrittenOffNum: dataListSelections[i].thisWrittenOffNum,
            writtenOffNum: dataListSelections[i].writtenOffNum,
            saleTotalAmount: dataListSelections[i].saleTotalAmount,
            status: 1
          })
        }
      },
      // 获取数据列表
      getReceiptDetailsByHeadId (id) {
        this.dataForm.headerId = id || 0
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl('/funds/receiptdetail/listAllByHeadId'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'headId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.init(id)
        })
      },

      // 销售订单选择
      saleOrderSelectHandle () {
        if (this.clientIdForSearch === '') {
          this.$message({
            message: '客户信息不能为空',
            type: 'warning'
          })
          return
        }

        this.saleOrderSelectVisible = true
        this.$nextTick(() => {
          this.saleOrderSelectInit(this.clientIdForSearch)
        })
      },

      // 获取数据列表
      saleOrderSelectInit (id) {
        this.dataForm.headerId = id
        this.innerVisible = true
        this.dataListLoading = true
        this.delList = []
        this.$http({
          url: this.$http.adornUrl('/sales/orderheader/listSaleOrdersByClientId'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'clientId': id
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },

      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/funds/receiptdetail/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 删除该行
      deleteRow (index, rows) {
        this.delList.push(rows[index].id)
        rows.splice(index, 1)
      },
      editRow (row) {
        row.status = 1
      },
      // 新增一行
      addRow () {
        this.dataList.push({
          saleOrderName: '',
          thisWrittenOffAmount: 0,
          status: 1
        })

        this.saleOrderSelectHandle()
      },
      // 分配收款金额
      distribution () {
        let totalAmount = this.dataForm.receiptAmount
        let len = this.dataList.length

        if (len === 0) {
          return
        }
        for (let i = 0; i < len; i++) {
          if (totalAmount < this.dataList[i].remainAmount) {
            this.dataList[i].thisWrittenOffAmount = totalAmount
            return
          } else {
            totalAmount = this.floatFormatter(totalAmount, this.dataList[i].remainAmount)
            this.dataList[i].thisWrittenOffAmount = this.dataList[i].remainAmount
          }
        }
      },

      floatFormatter (target, fromValue) {
        let r1, r2, m
        try { r1 = fromValue.toString().split('.')[1].length } catch (e) { r1 = 0 }
        try { r2 = target.toString().split('.')[1].length } catch (e) { r2 = 0 }

      // 动态控制精度长度
        m = Math.pow(10, Math.max(r1, r2))

        return parseInt((target - fromValue) * m, 10) / m
      },

      // 销售订单 远程搜索
      // queryString 为在框中输入的值
      // callback 回调函数,将处理好的数据推回
      querySearchAsync (queryString, callback) {
        this.s_girard = queryString === '' || queryString === null || queryString === 'undefined' ? '' : queryString

        let clientIdForSearch = this.dataForm.clientId === null ? '' : this.dataForm.clientId

        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/sales/orderheader/listSaleOrders`),
          method: 'get',
          params: this.$http.adornParams({
            'name': this.s_girard,
            'clientId': clientIdForSearch
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.names = data.saleOrdersMap.saleOrderNameDtoList
          } else {
            this.names = []
            this.$message.error(data.msg)
          }
        })
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          callback(this.names)
        }, 1000)
        // callback(this.names)
      },
      handleNameSelect (item, row) {
        console.log(item)
        row.saleOrderName = item.saleOrderName
        row.salesOrderHeaderId = item.salesOrderHeaderId
        row.saleOrderCode = item.saleOrderCode
        row.deposit = item.deposit
        row.writtenOffAmount = item.writtenOffAmount
        row.remainAmount = item.remainAmount
        row.saleDate = item.saleDate
        row.thisWrittenOffNum = item.thisWrittenOffNum
        row.writtenOffNum = item.writtenOffNum
        row.saleTotalAmount = item.saleTotalAmount
      },
      // 合计
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          // 本次核销金额(元)
          if (column.property === 'thisWrittenOffAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.thisWrittenOffAmount = sums[index]
          }
        })

        return sums
      },
      oninputMoney (num) {
        let str = num
        let len1 = str.substr(0, 1)
        let len2 = str.substr(1, 1)
        // 如果第一位是0，第二位不是点，就用数字把点替换掉
        if (str.length > 1 && len1 === 0 && len2 !== '.') {
          str = str.substr(1, 1)
        }
        // 第一位不能是.
        if (len1 === '.') {
          str = ''
        }
        // 限制只能输入一个小数点
        if (str.indexOf('.') !== -1) {
          let str_ = str.substr(str.indexOf('.') + 1)
          if (str_.indexOf('.') !== -1) {
            str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
          }
        }
        // 正则替换
        str = str.replace(/[^\d.]/g, '') // 保留数字和小数点
        str = str.replace(/\.\d\d\d$/, '') // 小数点后只能输两位
        return str
      },
      checkThisWrittenOffAmount (row) {
        this.checkReceiptAmount()

        if (row.thisWrittenOffAmount > row.remainAmount) {
          row.thisWrittenOffAmount = 0

          this.$message({
            message: '本次核销金额不能大于未核销金额',
            type: 'warning'
          })
        }
      },
      checkReceiptAmount () {
        if (this.dataForm.receiptAmount < this.thisWrittenOffAmount) {
          this.$message({
            message: '收款金额不能小于本次核销金额',
            type: 'warning'
          })
        }
      },
      tableRowClassName ({row, rowIndex}) {
        if (row.warning === 1) {
          return 'warning-row'
        }
        // else if (rowIndex === 3) {
        //   return 'success-row'
        // }
        return ''
      }

    }
  }
</script>
<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
